package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.DepartmentMapper;
import com.xxxx.server.pojo.Department;
import com.xxxx.server.service.IDepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-09-07
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getAllDept() {
        //需要返回的集合
        List<Department> result = new ArrayList<>();
        //数据中查询的记录
        final List<Department> list = this.list();

        /**
         * 循环遍历设置关系
         * 只要时没有上级的添加，否则全部设置关系
         */
        for (Department department : list) {
            if(department.getParentId()!=-1){
                //找到父级部门
                final Department dept = getDeptBy(list, department.getParentId());
                dept.addChildren(department);
            }else{
                result.add(department);
            }
        }

        return result;
    }

    @Override
    public boolean AddDep(Department department) {
        return this.saveOrUpdate(department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delDep(Integer id) {
        return this.retBool(departmentMapper.deleteById(id));
    }

    /**
     * 在dept集合中查询指定dept
     * @param list
     * @param id
     * @return
     */
    private Department getDeptBy(List<Department> list,Integer id) {
        for (Department department : list) {
            if(department.getId().equals(id)){
                return department;
            }
        }
        return null;
    }
    @Override
    public List<Department> selectDepartmentStatus() {
        return departmentMapper.selectDepartmentStatus();
    }
}
